<template>
  <n-data-table
    v-model:checked-row-keys="state.checkedRowKeys"
    striped
    :row-key="(row) => `${row.roleId}`"
    :columns="roleColumns"
    :data="state.list"
    :pagination="pagination"
    :max-height="props.height - 80"
    @update:checked-row-keys="onUpdate"
  />
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { roleApi } from '@/api/modules/role'

  const props = defineProps<{ height: number }>()
  const emits = defineEmits(['select'])

  const state = reactive({ list: [] as any[], checkedRowKeys: [] as any[] })

  const roleColumns = [
    {
      type: 'selection',
      multiple: true
    },
    { title: '编号', key: 'roleCode' },
    { title: '名称', key: 'roleName' }
  ]

  const pagination = reactive({
    page: 1,
    pageSize: 30,
    showSizePicker: true,
    pageSizes: [10, 30, 50, 100],
    onChange: (page: number) => {
      pagination.page = page
      findList()
    },
    onUpdatePageSize: (pageSize: number) => {
      pagination.pageSize = pageSize
      pagination.page = 1
      findList()
    }
  })

  onMounted(() => findList())

  const findList = () => {
    const params = { pageNum: pagination.page, pageSize: pagination.pageSize }
    roleApi.findListPage(params).then((resp: any) => {
      if (resp.success) {
        state.list = resp.data.list
      }
    })
  }

  const onUpdate = (
    keys: Array<string | number>,
    rows: object[],
    meta: { row: object | undefined; action: 'check' | 'uncheck' | 'checkAll' | 'uncheckAll' }
  ) => {
    let roles: any[] = []
    if (meta.action == 'check' || meta.action == 'uncheck') {
      const row = meta.row as any
      roles = [{ id: row.roleId, name: row.roleName, action: meta.action }]
    } else if (meta.action == 'checkAll' || meta.action == 'uncheckAll') {
      roles = state.list.map((r: any) => {
        return { id: r.roleId, name: r.roleName, action: meta.action }
      })
    }
    emits('select', roles)
  }

  const removeItem = (item: any) => {
    console.log(item)
    const idx = state.checkedRowKeys.indexOf(item.id)
    if (idx >= 0) {
      state.checkedRowKeys.splice(idx, 1)
    }
  }

  defineExpose({ removeItem })
</script>

<style lang="scss" scoped></style>
